package com.gecko.flutter_screen_capture;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

// 进程保活：无限循环播放无声音乐
public class KeepAliveService extends Service {
    private static final String TAG = "KeepAliveService";

    public static final String ACTION_CMD = "com.gecko.alive.cmd";
    public static final String ACTION_BUTTON_STOP = "com.gecko.alive.button_stop";
    public static final String EXTRA_CMD = "cmd";
    public static final int CMD_NULL = 0;
    public static final int CMD_START = 1;
    public static final int CMD_STOP = 2;

    public static final int GRAY_SERVICE_ID = 1001;
    public static final String CHANNEL_ID = "com.gecko.alive";
    public static final String CHANNEL_NAME = "Channel1";

    private MediaPlayer mMediaPlayer;
    private boolean forceStop = false;

    private static KeepAliveService sInst;

    public static class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equalsIgnoreCase(ACTION_CMD)) {
                int cmd = intent.getIntExtra(EXTRA_CMD, CMD_NULL);
                Log.i(TAG, "receive cmd:" + cmd);
                switch (cmd) {
                    case CMD_START:
                        break;
                    case CMD_STOP:
                        sInst.stop();
                        break;
                    default:
                        break;
                }
            } else if(intent.getAction().equalsIgnoreCase(ACTION_BUTTON_STOP)) {
                sInst.stop();
            }
        }
    }

    private Receiver mReceiver = new Receiver();

    //灰色保活
    public static class GrayInnerService extends Service {

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i(TAG, "GrayInnerService.onStartCommand()");
            sInst.sendNotification();
            stopForeground(true);
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sInst = this;

        Log.d(TAG, TAG + "---->onCreate,启动服务");
        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silent);
        mMediaPlayer.setLooping(true);
        forceStop = false;

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_CMD);
        intentFilter.addAction(ACTION_BUTTON_STOP);
        registerReceiver(mReceiver, intentFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                startPlayMusic();
            }
        }).start();
        sendNotification();
        return START_STICKY;
    }

    private void sendNotification() {
        NotificationChannel notificationChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(CHANNEL_ID,
                    CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setShowBadge(true);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(notificationChannel);
        }

        Notification notification;
        if(notificationChannel != null)
            notification = new Notification.Builder(this).setChannelId(CHANNEL_ID).build();
        else
            notification = new Notification();


        //设置service为前台服务，提高优先级
        if (Build.VERSION.SDK_INT < 18) {
            //Android4.3以下 ，隐藏Notification上的图标
            startForeground(GRAY_SERVICE_ID, notification);
        } else if (Build.VERSION.SDK_INT > 18 && Build.VERSION.SDK_INT < 25) {
            //Android4.3 - Android7.0，隐藏Notification上的图标
            Intent innerIntent = new Intent(this, GrayInnerService.class);
            startService(innerIntent);
            startForeground(GRAY_SERVICE_ID, notification);
        } else {
            //Android7.0以上app启动后通知栏会出现一条"正在运行"的通知
            startForeground(GRAY_SERVICE_ID, notification);
        }
    }

    private void startPlayMusic() {
        if (mMediaPlayer != null) {
            Log.d(TAG, "启动后台播放音乐");
            mMediaPlayer.start();
        }
    }

    private void stopPlayMusic() {
        if (mMediaPlayer != null) {
            Log.d(TAG, "关闭后台播放音乐");
            mMediaPlayer.stop();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopPlayMusic();
        unregisterReceiver(mReceiver);
        Log.d(TAG, TAG + "---->onCreate,停止服务");
        if(!forceStop) {
            // 重启自己
            Intent intent = new Intent(getApplicationContext(), KeepAliveService.class);
            startService(intent);
        }
    }

    // 主动停止
    public void stop() {
        Log.i(TAG, "force stop");
        stopSelf();
        stopForeground(true);
        forceStop = true;
    }
}
